//
//  main.cpp
//  第四章习题for Xcode
//
//  Created by asus on 2020/7/5.
//  Copyright © 2020 唐沈飞. All rights reserved.
//  本工程用于完成第四章习题

#include <iostream>
#include "KMP.hpp"
using namespace std;

//结点定义和宏在KMP.hpp中

void fun1(STR &str, STR ch1, STR ch2)
{
    /*
       1、将串str中所有值为ch1的字符替换为ch2的字符，若str为空或者串中不含ch1的字符，则不进行任何操作。
    
           str = "ababcbacbabcabdbsabccbcba";
           ch1 = "abc";
           ch2 = "xyz";
    */
    int nextval[4];
    GetNextVal(ch1, nextval);
    int pos = 1;
    while(pos != 0)
    {
        pos = KMP(str, ch1, nextval);
        if(str.length == 0 || pos == 0)
        return;         //判断主串是否为空或者主串是否已经匹配完成
        //若pos不为0，则说明匹配到了模式串 则进行替换工作
        else
        {
            int cnt = 0;
            while(ch2.str[++cnt] != '\0')
                str.str[pos++] = ch2.str[cnt];
        }
    }
    
}

void fun2(STR &str)
{
    /*
     2、实现str的逆转函数，如果str为空串则不作操作
     */
    int front = 1, rear = str.length;
    char temp;
    while(rear > front)
    {
        temp = str.str[front];
        str.str[front++] = str.str[rear];
        str.str[rear--] = temp;
    }
}

int main(int argc, const char * argv[]) {
    // insert code here...
    
    char str[] = "ababcbacbabcabdbsabccbcba";
    //char str[] = "abcbczyxsbdbazyxbcabzyxba";
    char ch1[] = "abc";
    char ch2[] = "xyz";
    STR S1, subS1, subS2;
    S1.length = 0;
    subS1.length = 0;
    subS2.length = 0;
    int i = 0;
    while(str[i++] != '\0')
    {
        S1.str[i] = str[i - 1];
        ++S1.length;
    }
    i = 0;
    while(ch1[i++] != '\0')
    {
        subS1.str[i] = ch1[i - 1];
        ++subS1.length;
    }
    i = 0;
    while(ch2[i++] != '\0')
    {
        subS2.str[i] = ch2[i - 1];
        ++subS2.length;
    }
    cout << S1.length << " " << subS1.length << " " << subS2.length << endl;
   
    for(int i = 0; i <= S1.length; i++)
        cout << S1.str[i];
    cout << endl;
    
    //第一题调试区域
    fun1(S1, subS1, subS2);
    for(int i = 0; i <= S1.length; i++)
        cout << S1.str[i];
    cout << endl;
    //第一题调试结束
    
    //第二题调试区域
    fun2(S1);
    for(int i = 0; i <= S1.length; i++)
        cout << S1.str[i];
    cout << endl;
    
    //第二题调试区域
    
    std::cout << "Hello, World!\n";
    return 0;
}
